package com.feng.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.reggie.dto.DishDto;
import com.feng.reggie.entity.Dish;
import com.feng.reggie.entity.DishFlavor;
import com.feng.reggie.mapper.DishMapper;
import com.feng.reggie.service.DIshService;
import com.feng.reggie.service.DishFlavorService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DIshService {

    @Autowired
    private DishFlavorService dishFlavorService;


   @Transactional
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        //保存菜品的基本信息到菜品表dish
        this.save(dishDto);
        //保存菜品口味数据到口味表
        Long dishId = dishDto.getId();
        //菜品口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历菜品口味表，将每个菜品口味打上菜品id的标签
        flavors=flavors.stream().map((item)->{
            item.setDishId(dishId);
            return item;
        }).collect(Collectors.toList());
         //保存菜品口味数据到菜品口味表
        dishFlavorService.saveBatch(flavors);


    }

    /**
     * 根据id查询菜品的信息和口味的信息
     * @param id
     */

    @Override
    public DishDto getByidWithFlavor(Long id) {
        //查询菜品的基本信息，从dish表查询
        Dish dish = super.getById(id);
        DishDto dishDto=new DishDto();
        //拷贝对象
        BeanUtils.copyProperties(dish,dishDto);
        //查询当前菜品对应的口味表，从dish_flavor查询
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId, id);
        List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
        dishDto.setFlavors(flavors);
        return dishDto;

    }

    /**
     * 更新菜品信息，同时更新口味信息
     * @param dishDto
     */

    @Override
    @Transactional
    public void updateWithFlavor(DishDto dishDto) {
       //更新菜品表基本信息
        super.updateById(dishDto);
       //先清理菜品对应的口味信息
        LambdaQueryWrapper<DishFlavor> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(queryWrapper);
       //再添加提交过来的口味数据
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors=flavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            return item;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(flavors);

    }


}
